package com.hang.runner;

import com.hang.entity.TenantDataSource;
import com.hang.mapper.TenantDataSourceMapper;
import com.hang.service.TenantDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DataSourceInitializer implements ApplicationRunner {
    @Autowired
    private TenantDataSourceMapper tenantDataSourceMapper;
    @Autowired
    private TenantDataSourceService tenantDataSourceService;

    @Override
    public void run(ApplicationArguments args) {
        // 1. 从主库加载所有租户数据源配置
        List<TenantDataSource> tenantDataSources = tenantDataSourceMapper.selectList(null);

        // 2. 遍历并动态注册数据源
        tenantDataSources.forEach(config -> {
            String tenantCode = config.getTenantCode();
            tenantDataSourceService.registerDataSource(tenantCode, config);
        });

        // 3. 打印日志验证
        System.out.println("启动时加载租户数据源完成，数量：" + tenantDataSources.size());
    }
}
